package com.huluobo.koltinim2003a.adapter

import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.huluobo.koltinim2003a.R
import com.huluobo.koltinim2003a.data.ContactListItem
import com.huluobo.koltinim2003a.ui.activity.ChatActivity
import com.huluobo.koltinim2003a.widget.ContactListItemView
import com.hyphenate.chat.EMClient
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/**
 * Created by lc on 2022/9/23.
 */
class ContactListAdapter(
    private val context: Context,
    private val contactListItems: MutableList<ContactListItem>
) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return ContactListItemViewHolder(ContactListItemView(context))
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        //数据绑定
        val contactListItemView = holder.itemView as ContactListItemView
        contactListItemView.bindView(contactListItems[position])

        val userName = contactListItems[position].userName

        contactListItemView.setOnClickListener {
            context.startActivity<ChatActivity>("username" to userName)
        }

        contactListItemView.setOnLongClickListener {
            val message = String.format(context.getString(R.string.delete_friend_message, userName))
            AlertDialog.Builder(context).setTitle(R.string.delete_friend_title)
                .setMessage(message)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(
                    R.string.confirm
                ) { _, _ -> deleteFriend(userName) }.show()
            true
        }
    }

    private fun deleteFriend(userName: String) {
        context.toast("删除成功:$userName")
        EMClient.getInstance().contactManager()
            .aysncDeleteContact(userName, object : EMCallbackAdapter() {
                override fun onSuccess() {
                    context.runOnUiThread {
                        toast(R.string.delete_friend_success)
                    }
                }

                override fun onError(code: Int, error: String?) {
                    context.runOnUiThread {
                        toast(R.string.delete_friend_failed)
                        Log.i("TagA", "deleteFriendError:$code,msg:$error")
                    }
                }
            })
    }

    override fun getItemCount(): Int = contactListItems.size

    class ContactListItemViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {

    }
}